package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDto;
import com.sky.entity.User;
import com.sky.exception.extend.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.IUserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    private static final String WX_LOGIN="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Override
    public User wechatLogin(UserLoginDto userLoginDto) {
        //1 首先获取openid
        String openid = getOpenId(userLoginDto.getCode());
        if (openid==null){
            //抛业务异常
            throw new LoginFailedException(MessageConstant.ACCOUNT_LOGIN_FAILED);
        }
        //2 调用UserMapper 根据openid来查询，用户是否注册过
        User user = userMapper.getByOpenId(openid);
        //3 判断用户对象是否为null
        if(user==null){
             user=User.builder()
                    .openid(openid)
                     .createTime(LocalDateTime.now())
                     .build();
            userMapper.register(user);
        }
        // 如果为null 那么自动进行注册 (根据openid和创建时间来插入到用户表)
        //4 返回登录的用户对象
        // git 测试
        return user;
    }

    /**
     * 根据 授权码来获取openid
     * @param code
     * @return
     */
    private String getOpenId(String code){
        //1 :封装map创建四个参数数据
        Map<String,String> map=new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        //2 使用工具类HttpClientUtil来返回json结果
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        //3 使用JSON.parseObject对象
        //4解析出openid 返回
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.get("openid").toString();
    }
}
